package com.fbms.module.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fbms.common.exception.ServiceException;
import com.fbms.common.utils.CommonBeanUtils;
import com.fbms.common.utils.StringUtils;
import com.fbms.module.auth.Bean.LoginUserDTO;
import com.fbms.module.auth.service.ISysLoginService;
import com.fbms.module.system.bean.entity.SysUser;
import com.fbms.module.system.dao.SysUserMapper;
import com.fbms.module.system.enums.UserStatusEnums;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 类描述：TODO
 *
 * @ClassName SysLoginServiceImpl
 * @Author HappyBoy
 * @Date 2023-03-20 15:48
 **/
@Service
public class SysLoginServiceImpl implements ISysLoginService {


    /**
     * 用户Mapper
     */
    private final SysUserMapper userMapper;

    @Autowired
    public SysLoginServiceImpl(SysUserMapper userMapper) {
        this.userMapper = userMapper;
    }

    /**
     * 用户登录
     * @param name 用户名
     * @param password 密码
     * @return 用户信息
     */
    @Override
    public LoginUserDTO login(String name, String password) {
        // 判断是否必填
        if(StringUtils.isAnyBlank(name, password)){
            throw new ServiceException("用户/密码必须填写");
        }

        // 查询用户是否存在
        SysUser sysUser = getSysUserByName(name);
        // 不存在 返回用户不存在
        if(sysUser == null){
            throw new ServiceException("用户不存在");
        }
        // 存在 用户异常状态 用户停用 用户删除
        String userStatus = sysUser.getStatus();
        if(UserStatusEnums.isDeleted(userStatus)){
            throw new ServiceException("用户已删除");
        }

        if(UserStatusEnums.isDisable(userStatus)){
            throw new ServiceException("用户已停用");
        }

        String realPassword = sysUser.getPassword();

        // 验证密码正确性
        // 密码不正确 返回密码错误
        if(!password.equals(realPassword)){
            throw new ServiceException("用户密码不正确");
        }

        // 密码正确 返回正确结果
        return CommonBeanUtils.doToDto(sysUser, LoginUserDTO.class);
    }

    /**
     *
     * @param name 名称
     * @return 用户信息
     */
    private SysUser getSysUserByName(String name) {
        LambdaQueryWrapper<SysUser> query = new LambdaQueryWrapper<>();
        query.eq(SysUser::getName, name);
        return userMapper.selectOne(query);
    }

}
